from django.db import models
from django.forms.models import ModelForm
from Exams.customfunctions import calculate_grade
from Exams.models import Exam, ExamOption, ExamQuestion, ExamUser, StudentExam, StudentAnswer
from pprint import pprint

class OptionsForm(ModelForm):
    option = models.CharField()

class QuestionForm(ModelForm):
    question = models.CharField(max_length=120)
    options = []
    correctAnswer = models.CharField(max_length=20)


class ExamForm():
    id = models.IntegerField()
    title = models.CharField(max_length=120)
    description = models.TextField()
    deadline = models.CharField(120)
    enabled=models.BooleanField()
    questions = []

#serialize and save to db
def SaveExamDataToDb(postedExam, username ):
    #todo: validation

    ex = Exam() #create new Exam object to populate and save
    if not 'questions' in postedExam:
        return False

    #pprint(postedExam['questions'])

    ex.title = postedExam['title']

    ex.description = postedExam['description']

    ex.deadline = postedExam['deadline']

    ex.author = ExamUser.objects.get(user_name = username)

    #ex.datecreated = ";models.DateTimeField(auto_now=True)

    ex.enabled = True

    ex.save() #save so we get an id

    exId = ex.id

    #get questions list object
    questions = postedExam['questions']

    #loop through all questions
    for q in questions:
        #create a new question for each iteration
        if not 'options' in q:
            return False
        exQuestion = ExamQuestion()
        exQuestion.exam_id = Exam.objects.get(pk=exId)
        exQuestion.question = q['question']
        exQuestion.save()
        qId = exQuestion.id #get the new id
        for o in q['options']:
            qOption = ExamOption()
            qOption.exam_question_id = ExamQuestion.objects.get(pk=qId)
            qOption.answer_option = o['option']
            qOption.is_correct = bool( o['correct'])
            qOption.save()

        # return true for success
    return True

#a helper function that saves posted data to db when a student takes an exam
#input postedAnswers a Json object containing the post data
#username containing the username exam taker...
#returns True if successfull and crashes otherwise !!
def saveStudentAnswers(postedAnswers, username):
    pprint(username)
    pprint(postedAnswers)
    student = ExamUser.objects.get(user_name = username)

    eId = postedAnswers['eid']
    pprint( "Exam id: " + str(eId) + " user id: " + str(student.id))

    try:
        se = StudentExam.objects.get(exam_id =eId,student = student.id)
        #se = StudentExam.objects.raw(
        #   "select * from exams_studentexam where exam_id_id = " + str(eid) + " and student_id = " + str(student.id))
    except StudentExam.DoesNotExist:
        sEx = StudentExam()
        sEx.exam_id = Exam.objects.get(pk=eId)
        sEx.student = ExamUser.objects.get(user_name = username)
        sEx.exam_grade = 0 #we have not calculated the grade yet
        sEx.save()
        studentExamId = sEx.id #now we have the new id of the newly created record

        #then loop through the answers
        answers = postedAnswers['answers']

        for a in answers:
            sAns = StudentAnswer()
            sAns.student = ExamUser.objects.get(user_name = username)
            sAns.option_id = ExamOption.objects.get(pk= a['answered_option'])
            sAns.question_id = ExamQuestion.objects.get(pk=a['question_id'])
            sAns.save() #save each exam answer to a question

        return True
